import React, { useState, useEffect } from "react";
import { Flex, Toast } from "antd-mobile";
import {
  List,
  AutoSizer,
  WindowScroller,
  InfiniteLoader,
} from "react-virtualized";
// 导入搜素导航栏
import SearchHeader from "../../components/SearchHeader";
// 导入筛选栏组件
import Filter from "./components/Filter";
// 导入房屋列表组件
import HouseItem from "../../components/HouseItem";
// 导入吸顶组件
import Sticky from "../../components/Sticky";
// 导入没有房源提示组件
import NoHouse from "../../components/NoHouse";
import { getCurrentCity } from "../../utils/index";

import API from "../../utils/api";
import { addHistory } from "../../utils/history";

import { BASE_URL } from "../../utils/url";

// 导入样式
import styles from "./index.module.css";

export default function HouseList(props) {
  const [label, setlabel] = useState("");
  const [value, setvalue] = useState("");
  const [isLoading, setisLoading] = useState(false);
  const [filters, setfilters] = useState({});
  const [list, setlist] = useState([]);
  const [count, setcount] = useState(0);

  useEffect(() => {
    // 获取房屋列表数据
    const searchHouseList = async () => {
      const { label, value } = await getCurrentCity();
      setlabel(label);
      setvalue(value);
      setisLoading(true);
      Toast.loading("Loading...", 0, null, false);
      const res = await API.get("/houses", {
        params: {
          cityId: value,
          ...filters,
          start: 1,
          end: 30,
        },
      });

      const { list, count } = res.data.body;
      setlist(list);
      setcount(count);
      setisLoading(false);
      Toast.hide();
      if (count !== 0) {
        Toast.info(`共找到 ${count} 套房源`, 2, null, false);
      }
    };
    searchHouseList();
  }, [filters]);

  // 接收Filter 组件中房屋筛选条件数据
  const onFilter = (filters) => {
    setfilters(filters);
    // 点击确定按钮时， 页面回到顶部
    window.scrollTo(0, 0);
  };

  // List组件渲染每一行的方法：
  const renderHouseList = ({ key, index, style }) => {
    const handleClick = () => {
      props.history.push(`/detail/${house.houseCode}`);
      // 添加浏览记录
      addHistory(house);
    };
    // 根据index获取每一行的数据
    const house = list[index];

    if (!house) {
      return (
        <div key={key} style={style} className={styles.loading}>
          <p>Loading...</p>
        </div>
      );
    }

    return (
      <HouseItem
        key={key}
        onClick={handleClick}
        style={style}
        src={BASE_URL + house.houseImg}
        title={house.title}
        desc={house.desc}
        tags={house.tags}
        price={house.price}
      />
    );
  };

  // 渲染列表项
  const renderHouseItem = () => {
    if (count === 0 && !isLoading) {
      return <NoHouse>没有找到合适房源，换个条件试试吧 ~ ~</NoHouse>;
    }

    return (
      <InfiniteLoader
        isRowLoaded={isRowLoaded}
        loadMoreRows={loadMoreRows}
        rowCount={count}
      >
        {({ onRowsRendered, registerChild }) => (
          <WindowScroller>
            {({ height, isScrolling, scrollTop }) => (
              <AutoSizer>
                {({ width }) => (
                  <List
                    onRowsRendered={onRowsRendered}
                    ref={registerChild}
                    autoHeight
                    width={width} // 视口宽度
                    height={height} // 视口高度
                    rowCount={count} // 行数
                    rowHeight={120} // 行高
                    rowRenderer={renderHouseList} // 渲染每一行
                    isScrolling={isScrolling}
                    scrollTop={scrollTop}
                  />
                )}
              </AutoSizer>
            )}
          </WindowScroller>
        )}
      </InfiniteLoader>
    );
  };

  // 判断列表中每一行数据是否加载完成
  const isRowLoaded = ({ index }) => {
    return !!list[index];
  };

  // 获取更多房屋列表数据  该方法返回 Peomise 对象, 并且数据加载完时要被解决
  const loadMoreRows = ({ startIndex, stopIndex }) => {
    return new Promise((resolve) => {
      API.get("/houses", {
        params: {
          cityId: value,
          ...filters,
          start: startIndex,
          end: stopIndex,
        },
      }).then((res) => {
        setlist([...list, ...res.data.body.list]);
      });
    });
  };

  return (
    <div className={styles.root}>
      {/* 搜索导航栏 */}
      <Flex className={styles.header}>
        <i
          className="iconfont icon-back"
          onClick={() => props.history.goBack()}
        />
        <SearchHeader currentCity={label} className={styles.searchHeader} />
      </Flex>

      {/* 分选栏 */}
      <Sticky height={40}>
        <Filter onFilter={onFilter} />
      </Sticky>

      {/* 房屋列表 */}
      <div className={styles.houseItems}>{renderHouseItem()}</div>
    </div>
  );
}
